package com.hua.argi;

/**
 * @author: _hua
 * @created: 2019/3/31.
 * @updater:
 * @description:
 */
public class BinarySearch {

    public static void main(String args[]){
        int array[] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9};
        System.out.println(findTwoPoint(array,6));;
        System.out.println(search(array,6,0,8));;
    }
    /**
     * 找到目标值返回数组下标，找不到返回-1
     * @param array
     * @param key
     * @return
     */
    public static int findTwoPoint(int[] array,int key){
        int start = 0;
        int last = array.length-1;
        while (start<=last){
            int mid =start+(last-start)/2;

            if(key==array[mid]){
                return mid;
            }

            if(key>array[mid]){
                start=mid+1;
            }

            if(key<array[mid]){
                last=mid-1;
            }
        }

        return -1;
    }

    public static int search(int[] array,int key,int low,int high){
        int mid =low+(high-low)/2;
        if(key==array[mid]){
            return mid;
        }else if(key>array[mid]){
            return search(array,key,mid+1,high);
        }else if(key<array[mid]){
            return search(array,key,low,mid-1);
        }else {
            return -1;
        }
    }
}
